package com.xiaoyu.client.ui.activity.nearby;


import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreator;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreator;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.model.nearby.MyRecommendBean;
import com.xiaoyu.client.model.nearby.MyRecommendBean.DataBean.ListBean;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.home.NearbyShopsActivity;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.adapter.AllPowerfulAdapter;
import com.xiaoyu.commonlib.utils.LongitudeAndLatitude;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author jx
 * @date 创建时间 2018/11/14
 * @Description 我的推荐 -- 等待审核、已通过、已驳回
 */
@SuppressLint("ValidFragment")
public class MyRecommendationFragment extends Fragment {
    private View mView;
    private List<ListBean> mAvailableList = new ArrayList<>();
    private AllPowerfulAdapter mMyAdapter;
    @BindView(R.id.common_recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.smart_refresh_layout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.common_recycler_view_empty_page)
    ImageView mEmptyPage;
    private int page = 1;//当前页数
    private int totalPage;//总页数
    private int state = 1;//状态
    private int type;//1、未审核 2、已通过审核 0、已驳回
    public LocationClient mLocationClient = null;
    private String lat;//纬度
    private String lng;//经度

    public MyRecommendationFragment(int type) {
        this.type = type;
        switch (type) {
            case 1:
                state = 1;
                break;
            case 2:
                state = 2;
                break;
            case 0:
                state = 0;
                break;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (mView == null) {
            mView = inflater.inflate(R.layout.common_recycler_view, container, false);
            //绑定fragment
            ButterKnife.bind(this, mView);
            initView();
        }
        ViewGroup parent = (ViewGroup) mView.getParent();
        if (parent != null) {
            parent.removeView(mView);
        }
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        page = 1;
        mAvailableList.clear();
        mMyAdapter.notifyDataSetChanged();
        mRefreshLayout.setNoMoreData(false);
        ToastUtil.log(state + "");
        mLocationClient.start();
        getRecommendList();
    }

    private void initView() {
        //初始化定位对象
        mLocationClient = new LocationClient(getActivity());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setCoorType("GCJ02");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setIsNeedAddress(true);
        mLocationClient.setLocOption(option);

        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        setMyAdapter(mAvailableList);
        //上拉下拉刷新设置
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsHeader(context);
            }
        });
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                return new ClassicsFooter(context).setDrawableSize(20);
            }
        });

        mRefreshLayout.setOnRefreshListener(onRefreshListener);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);
        mRefreshLayout.setNoMoreData(false);
    }

    /**
     * 定位监听
     */
    private BDAbstractLocationListener myListener = new BDAbstractLocationListener() {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            Log.i("xiaoyuu", "经纬度  经度： " + bdLocation.getLongitude() + "   纬度：  " + bdLocation.getLatitude()
                    + "   街道： " + bdLocation.getStreet() + "   type = " + bdLocation.getLocType()
                    + "   省份 ： " + bdLocation.getProvince() + "  城市： " + bdLocation.getCity() + "  addstr : " + bdLocation.getAddrStr()
                    + "  描述：" + bdLocation.getLocationDescribe());
            lat = String.valueOf(bdLocation.getLatitude());
            lng = String.valueOf(bdLocation.getLongitude());
            getRecommendList();
            mLocationClient.stop();
        }
    };

    private void setMyAdapter(List<ListBean> mAvailableList) {
        mMyAdapter = new AllPowerfulAdapter<ListBean>(R.layout.service_station_item, mAvailableList, new AllPowerfulAdapter.OnClickListener<MyRecommendBean.DataBean.ListBean>() {
            @Override
            public void setOnClick(BaseViewHolder baseViewHolder, ListBean listBean, int position) {
                Intent intent = new Intent(getActivity(), ShopDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_NEARBY_STORE_MY_RECOM);
                bundle.putString(ClientConstants.STORE_ID, listBean.getStore_id());
                intent.putExtras(bundle);
                startActivity(intent);
            }
        }) {
            @Override
            protected void convert(BaseViewHolder baseViewHolder, ListBean dataBean) {
                super.convert(baseViewHolder, dataBean);
                ImageView shopImg = baseViewHolder.getView(R.id.service_station_item_img);//店铺图片
                Glide.with(MyRecommendationFragment.this).load(dataBean.getStore_image()).into(shopImg);
                baseViewHolder.setText(R.id.service_station_item_title, dataBean.getStore_name());//店铺名字
                baseViewHolder.setText(R.id.service_station_item_location, dataBean.getStore_city() + dataBean.getStore_address());//店铺地址
                baseViewHolder.setText(R.id.service_station_item_distance, dataBean.getDistance());//店铺距离
                LinearLayout tagLayout = baseViewHolder.getView(R.id.service_station_item_tag_layout);
                tagLayout.removeAllViews();
                for (int i = 0; i < dataBean.getTag_list().size(); i++) {
                    TextView textView = new TextView(getActivity());
                    textView.setPadding(UIUtils.dip2px(10), 0, UIUtils.dip2px(10), 0);
                    textView.setBackgroundColor(Color.parseColor(dataBean.getTag_list().get(i).getTag_color()));
                    textView.setText(dataBean.getTag_list().get(i).getTag_name());
                    textView.setTextSize(11);
                    textView.setGravity(Gravity.CENTER);
                    textView.setTextColor(Color.WHITE);
                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, UIUtils.dip2px(22));
                    if (i == 0) {
                        layoutParams.setMargins(0, 0, 0, 0);
                    } else {
                        layoutParams.setMargins(UIUtils.dip2px(12), 0, 0, 0);
                    }
                    tagLayout.addView(textView, layoutParams);
                }
            }
        };
        mRecyclerView.setAdapter(mMyAdapter);
    }

    //刷新监听
    private OnRefreshListener onRefreshListener = new OnRefreshListener() {
        @Override
        public void onRefresh(@NonNull RefreshLayout refreshLayout) {
            page = 1;
            mAvailableList.clear();
            getRecommendList();
            mRefreshLayout.finishRefresh();
        }
    };

    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < totalPage) {
                page = page + 1;
                getRecommendList();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                ToastUtil.showBelowToast(getActivity(), "已经没有更多数据！！！");
            }
        }
    };


    /**
     * 获取我的推荐列表
     */
    private void getRecommendList() {
        NetworkManager.getMyRecommend(page, PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), state, lat, lng, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                succeedResult(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }

    private void succeedResult(String result) {
        if (page == 1) {
            mAvailableList.clear();
            mMyAdapter.notifyDataSetChanged();
        }
        MyRecommendBean bean = new Gson().fromJson(result, MyRecommendBean.class);
        mAvailableList.addAll(bean.getData().getList());
        if (bean.getData().getList().size() == 0) {
            mRefreshLayout.setEnableLoadMore(false);
            mRefreshLayout.setEnableRefresh(false);
            mEmptyPage.setVisibility(View.VISIBLE);
            if (type == 1 || type == 2 || type == 0) {
                mEmptyPage.setImageResource(R.mipmap.no_data);
            }
            return;
        }
        totalPage = Integer.parseInt(bean.getData().getCount());
        mMyAdapter.notifyDataSetChanged();
    }

}
